package com.pms.manager;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Session;
import org.springframework.stereotype.Service;

import com.googlecode.cswish.oosearch.QLInfo;
import com.googlecode.cswish.struts.spring.GenericService;
import com.pms.house.House;

@Service
public class DebitChargeItemStandardService {

	@Resource
	GenericService genericService;
	
	protected EntityManager em;
	
	@PersistenceContext(unitName="espirit")
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}
	
	public void add(DebitChargeItemStandard model){
		model = genericService.add(model);
		reSetHouseChargeItemStandard(model);
	}
	
	public DebitChargeItemStandard update(DebitChargeItemStandard model){
		model = genericService.update(model);
		reSetHouseChargeItemStandard(model);
		return model;
	}
	
	private void reSetHouseChargeItemStandard(DebitChargeItemStandard model){
		if (model == null || model.getId() == null) return ;
		Collection<Integer> houseIds = getHouseIds(model);
		String ql = "delete from " + HouseDebitChargeItemStandard.class.getName();
		getSession().createQuery(ql).executeUpdate();
		for(Integer id : houseIds){
			House house = genericService.load(House.class, id);
			HouseDebitChargeItemStandard hdcis = new HouseDebitChargeItemStandard();
			hdcis.setDebitChargeItemStandard(model);
			hdcis.setHouse(house);
			genericService.add(hdcis);
		}
	}
	
	private Collection<Integer> getHouseIds(DebitChargeItemStandard model){
		Collection<Integer> results = new HashSet<Integer>();
		if (model == null || model.getId() == null) return Collections.EMPTY_LIST;
		if (model.getGardenIds() != null){
			String[] gardenIds = model.getGardenIds().split(",");
			for(String id : gardenIds){
				Integer gardenId = Integer.valueOf(id);
				House example = new House();
				String ql = "from " + House.class.getName() + " a where a.building.garden.id=?";
				List<House> houses = genericService.searchByQl(new QLInfo(ql, true, gardenId)).getData();
				if (houses != null){
					for(House house : houses){
						results.add(house.getId());
					}
				}
			}
		}
		if (model.getBuildingIds() != null){
			String[] buildingIds = model.getBuildingIds().split(",");
			for(String id : buildingIds){
				Integer buildingId = Integer.valueOf(id);
				House example = new House();
				String ql = "from " + House.class.getName() + " a where a.building.id=?";
				List<House> houses = genericService.searchByQl(new QLInfo(ql, true, buildingId)).getData();
				if (houses != null){
					for(House house : houses){
						results.add(house.getId());
					}
				}
			}
		}
		if (model.getHouseCodes() != null){
			
		}
		return results;
	}
	
	public Session getSession(){
		return (Session)em.getDelegate();
	}
}
